<template>
  <el-dialog
      v-model="dialogVisible"
      title="经费报销"
      :close-on-click-modal="false"
      width="80%"
      @close="handleDialogClose"
  >
    <div  v-loading="loading">
      <div class="dialog-box">
        <div>
          <div class="dialog-one-title">项目信息</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="项目名称">{{projectInfo.name}}</el-descriptions-item>
            <el-descriptions-item label="批准经费">{{ turnWanyuan(projectInfo.feeAuthorize) }}</el-descriptions-item>
            <el-descriptions-item label="负责人">{{ projectInfo.chargerName }}</el-descriptions-item>
            <el-descriptions-item label="所属单位">{{ projectInfo.unitName }}</el-descriptions-item>
            <el-descriptions-item label="开始日期">{{ projectInfo.beginDate }}</el-descriptions-item>
            <el-descriptions-item label="计划完成日期">{{ projectInfo.planEndDate }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <div>
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
                  @sort-change="handleSortChange">
          <el-table-column label="项目名称" prop="projectName"  sortable="p.name">
          </el-table-column>
          <el-table-column prop="chargerName" label="负责人" ></el-table-column>
          <el-table-column prop="payoutFee" label="支出金额（元）" ></el-table-column>
          <el-table-column prop="payoutDate" label="支出时间" sortable="b.payout_date"></el-table-column>
          <el-table-column prop="note" label="摘要" sortable="b.note"></el-table-column>
          <el-table-column prop="unitName" label="所属单位" ></el-table-column>
          <el-table-column sortable="b.checkstatus" prop="checkstatus" label="审核状态">
            <template #default="{ row }">
              <CommonLabel :dataList="checkStatusList" valueKey="dictValue" labelKey="dictLabel"
                           :value="row.checkstatus" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="230">
            <template #default="scope">
              <!-- 科研人员 -->
              <el-button v-if="verifyRoleType.isKyry() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)"
                         type="primary" plain size="small" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button v-if="verifyRoleType.isKyry() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)"
                         type="danger" plain size="small" @click="handleDelete(scope.row)">
                删除
              </el-button>
              <el-button v-if="verifyRoleType.isKyry() && scope.row.checkstatus == 2"
                         @click="DetailsDialogBtn(scope.row)" plain type="primary" size="small">
                查看
              </el-button>
              <el-button v-if="verifyRoleType.isKyry() && scope.row.checkstatus == 1"
                         plain type="warning" size="small" @click="handleCancel(scope.row)"
                         >
                撤销
              </el-button>

              <!-- 科研管理员 -->
              <el-button v-if="verifyRoleType.iskycgly() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)"
                         type="primary" plain size="small" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button v-if="verifyRoleType.iskycgly() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)"
                         @click="DetailsDialogBtn(scope.row)" plain type="primary" size="small">
                查看
              </el-button>
              <el-button v-if="verifyRoleType.iskycgly() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)"
                         type="danger" plain size="small" @click="handleDelete(scope.row)"
                        >
                删除
              </el-button>
              <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 1"
                         type="primary" plain size="small" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 1"
                         @click="DetailsDialogBtn(scope.row)" plain type="primary" size="small">
                查看
              </el-button>
              <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 1 && scope.row.isAuditor"
                         @click="DetailsDialogBtn(scope.row)" plain type="success" size="small">
                审核
              </el-button>
              <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 2"
                         @click="DetailsDialogBtn(scope.row)" plain type="primary" size="small">
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="example-pagination-block">
          <el-pagination layout="->,prev, pager, next, total" :total="count" currentPage1="10"
                         @current-change="handleCurrentChange" />
        </div>
      </div>

      <jfzcDialogCompile ref="RefDialog" @Getlist="getslist"></jfzcDialogCompile>
      <jfzcDialogadd ref="addDialog" @Getlist="getslist"></jfzcDialogadd>
      <jfzcDialogDetails  @Getlist="getslist" ref="DetailsDialog"></jfzcDialogDetails>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { turnWanyuan } from '@/utils/money.js';
import {  getEditInfo,selectVproject} from "@/api/money/jfzcApi.js";
import {verifyRoleType} from "@/utils/main.js";

const dialogVisible = ref(false)
const ID = ref('')
const loading = ref(false) // 添加加载状态
const openjfbxsqTable = function (x){
  ID.value = x
  GetselectVproject(x)

  dialogVisible.value = true
}
const GetselectVproject = (x) => {
  selectVproject({
    pageNum: 1,
    pageSize: 50,
    projectId:x,
  })
      .then((res) => {
        projectInfo.value = res.rows[0]
        getslist()
      })
}

const  projectInfo = ref({
  projectId: "", // 项目下拉id
  projectName: "", // 项目，名称
  feeAuthorize: "",
  chargerName: "", // 负责人
  unitName: "", // 所属单位
  beginDate: "", // 开始事件
  planEndDate: "", // 计划结束事件
  isAuditor:false, //是否审核
  processInstanceId:'',//新加的行数据带来的id
  taskId:'',//新加的行数据带来的id
  feeChargerName: "", // 负责人名称
  feeCardNum: "", // 经费卡号
  incomeTotal: "", // 累计入账
  entryBalance: "",
  adjustmentFee: "0", // 调整量
  afterFee: "",
  alterreason: ""
})
// 暴露 openDialog 方法供父组件调用
defineExpose({
  openjfbxsqTable,
});
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import useDictFetch from "@/hooks/useDictFetch";
const checkStatusList = useDictFetch("bpm_process_instance_status"); //审核状态
import {onBeforeMount, ref} from "vue";
const openaudit = ref(null)
const openauditBtn = function (row){
  openaudit.value.openaudit(row)
}
const getListParme = defineModel();
import {
  list,
} from '@/api/money/jfzcApi'
import jfzcDialogCompile from "@/views/money/jfzc/jfzcDialogCompile.vue";
import jfzcDialogadd from "@/views/money/jfzc/jfzcDialogadd.vue";
import jfzcDialogDetails from "@/views/money/jfzc/jfzcDialogDetails.vue";
import {remove} from "@/api/money/jfzcApi";
import {ElMessage, ElMessageBox} from "element-plus";
const DetailsDialog = ref(null)
const DetailsDialogBtn = (row , name) => {
  DetailsDialog.value.openDialog(row , name)
}

const RefDialog  = ref(null)

const openDialog = () => {
  RefDialog.value.openDialog()
}

//请求列表
const getslist = function () {
  list({
    pageNum:1,
    pageSize:10,
    projectId:projectInfo.value.projectId,
    orderByColumn:" b.payout_date",
    isAsc: "descending"
  }).then((res)=>{
    count.value = res.total
    tableData.value = res.rows

  })

}

//分页
const count = ref(0)
const handleCurrentChange = (val: number) => {
  console.log(`${val} items per page`)
  list({
    pageNum:val,
    pageSize:10,
    projectId:projectInfo.value.projectId,
  }).then((res)=>{
    count.value = res.total
    tableData.value = res.rows

  })
}
// 处理排序变化的方法
const handleSortChange = (row) => {
  getListParme.value.orderByColumn = row.column.sortable;
  getListParme.value.isAsc=row.order;
  getslist();
};
//撤销
import { cancelProcess } from "@/api/project/common";
//点击撤销
const handleCancel = async (row) => {
  loading.value = true // 开始加载
  try {
    const res = await cancelProcess(row.processInstanceId);
    if (res.data) {
      ElMessage({
        message: "操作成功！",
        type: "success",
      });
      getslist()
    } else {
      ElMessage({
        message: "操作失败！",
        type: "warning",
      });
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false // 结束加载
  }
};

// 定义表格数据
const tableData = ref([

]);

// 存储选中的行数据
const selectedProjects = ref([]);

// 处理复选框选择变化的方法
const handleSelectionChange = (val) => {
  selectedProjects.value = val;
};
const handleDeleteS = () => {
  if(selectedProjects.value.length < 1){
    ElMessage({
      type: 'info',
      message: '请选择删除项',
    })
  }else {
    ElMessageBox.confirm(
        '确认！删除这条数据?',
        '提醒',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(() => {
          const idString = selectedProjects.value.map(item => item.id).join(',');
          remove(idString)
              .then((res)=>{
                if(res.code == 200){
                  ElMessage({
                    type: 'success',
                    message: res.msg,
                  })
                  getslist()
                }else {
                  ElMessage({
                    type: 'info',
                    message: res.msg,
                  })
                }
              })
        })
        .catch(() => {
        })
  }
}

const addDialog = ref(null)
// 处理编辑操作
const handleEdit = (row) => {
  addDialog.value.openDialog(row)
};
// 定义关闭事件回调
const emits = defineEmits(['emptyData']); // 定义上抛事件

// 对话框关闭时的处理函数
const handleDialogClose = () => {
  if (tableData.value.length === 0) {
    emits('emptyData'); // 表格数据为空时上抛事件
  }
};
// 处理删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确认！删除这条数据?',
      '提醒',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        loading.value = true // 开始加载
        remove(row.id)
            .then((res)=>{
              if(res.code == 200){
                ElMessage({
                  type: 'success',
                  message: res.msg,
                })
                emits('emptyData');
                getslist()

              }else {
                ElMessage({
                  type: 'info',
                  message: res.msg,
                })
              }
            })
            .finally(() => {
              loading.value = false // 结束加载
            })
      })
      .catch(() => {
      })
}

const drawer = ref(false) //更多在弹出
function cancelClick() {
  drawer.value = false
}

//时间区间选择
const optionsdata = [
  {
    value: 'daterange',
    label: '年/月/日',
  },
  {
    value: 'monthrange',
    label: '月',
  },
  {
    value: 'yearrange',
    label: '年',
  },
]

const year = ref<'daterange' | 'monthrange' | 'yearrange'>('daterange')

const valueDate = ref([])
//时间区间选择end
//判断复选框
const isRowSelectable = (row) => {
  return row.checkstatus!== '1' && row.checkstatus!== '2';
};

</script>

<style scoped lang="scss">
.flex-input{
  display: flex;
  margin: 10px 5px 10px 0;
}
.flex-input > div{
  margin-right: 10px;
  width: 50%;
}
.data-flex{
  display: flex;
  margin: 0 3px;
  div:first-child{
    margin-right: 10px;
  }
}
.sss > div{
  margin: 5px 3px;
  width: 100%;
}
.zhi{
  margin: 0 10px;
}
.input-container {
  display: flex;
  align-items: center;
  gap: 10px;
}
.btns {
  margin-bottom: 20px;
}
.clickable-status{
  color:#23527c;
}
.clickable-status:hover{
  color:#23527c;
  cursor: pointer;
  text-decoration: underline;
}
</style>